export default {
  methods: {
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 和 Png 格式!");
        return false;
      }
      /* 图片压缩 */
      const _this = this
      return new Promise(resolve => {
        const reader = new FileReader()
        const image = new Image()
        image.onload = () => {
          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          const originWidth = image.width
          const originHeight = image.height
          // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
          let maxWidth = 1280, maxHeight = 1280
          // 目标尺寸
          let targetWidth = originWidth, targetHeight = originHeight
          // 图片尺寸超过800x800的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更宽，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
          }
          canvas.width = targetWidth
          canvas.height = targetHeight
          context.clearRect(0, 0, targetWidth, targetHeight)
          context.drawImage(image, 0, 0, targetWidth, targetHeight)
          const dataUrl = canvas.toDataURL('image/jpeg', 0.8)
          const blobData = _this.dataURItoBlob(dataUrl, 'image/jpeg')
          resolve(blobData)
        }
        reader.onload = (e => { image.src = e.target.result; })
        reader.readAsDataURL(file)
        return true;
      })
    },
    /* 将base64转换为blob */
    dataURItoBlob(dataURI, type) {
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {type: type});
    }
  }
}